<template>
  <div class="fitness-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>健身课程管理</span>
          <div class="header-actions">
            <el-input
              v-model="searchQuery"
              placeholder="搜索课程..."
              style="width: 200px; margin-right: 16px"
              clearable
            />
            <el-button type="primary" @click="handleAdd">添加课程</el-button>
          </div>
        </div>
      </template>

      <el-table 
        :data="filteredCourses" 
        style="width: 100%"
        :header-cell-style="{
          textAlign: 'center'
        }"
      >
        <el-table-column prop="courseId" label="ID" width="80" align="center" />
        <el-table-column prop="title" label="课程名称" width="200" align="center" />
        <el-table-column prop="category" label="分类" width="120" align="center" />
        <el-table-column prop="instructor" label="教练" width="120" align="center" />
        <el-table-column prop="level" label="难度" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getLevelType(scope.row.level)">
              {{ scope.row.level }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="时长" width="100" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 课程表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加课程' : '编辑课程'"
      width="600px"
      destroy-on-close
    >
      <el-form 
        ref="courseFormRef"
        :model="courseForm" 
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="课程名称">
          <el-input v-model="courseForm.title" />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="courseForm.category">
            <el-option label="瑜伽" value="瑜伽" />
            <el-option label="力量训练" value="力量训练" />
            <el-option label="有氧运动" value="有氧运动" />
            <el-option label="拉伸放松" value="拉伸放松" />
          </el-select>
        </el-form-item>
        <el-form-item label="教练ID">
          <el-input 
            v-model="courseForm.expertId"
            placeholder="请输入教练ID"
            type="number"
          />
        </el-form-item>
        <el-form-item label="难度">
          <el-select v-model="courseForm.level">
            <el-option label="基础课程" value="基础课程" />
            <el-option label="进阶课程" value="进阶课程" />
          </el-select>
        </el-form-item>
        <el-form-item label="时长">
          <el-input v-model="courseForm.duration" />
        </el-form-item>
        <el-form-item label="课程介绍">
          <el-input 
            v-model="courseForm.description" 
            type="textarea" 
            rows="3"
          />
        </el-form-item>
        <el-form-item label="封面图片">
          <el-input v-model="courseForm.coverImage" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="courseForm.status">
            <el-option label="已发布" value="已发布" />
            <el-option label="已下架" value="已下架" />
            <el-option label="未发布" value="未发布" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCourseList, addCourse, updateCourse, deleteCourse, getExpertInfo } from '@/api/admin/course'

// 搜索和分页
    const searchQuery = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
const total = ref(0)

// 表单相关
    const dialogVisible = ref(false)
    const dialogType = ref('add')
const courseFormRef = ref(null)
    const courseForm = ref({
  courseId: '',
      title: '',
      category: '',
  expertId: '',
      instructor: '',
  level: '基础课程',
      duration: '',
      description: '',
  coverImage: '',
  status: '未发布'
})

// 课程数据
const courses = ref([])

// 添加教练 ID 输入框的验证事件
const validateExpertId = async (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入教练ID'))
    return
  }
  try {
    const expertInfo = await getExpertInfo(parseInt(value))
    if (!expertInfo) {
      callback(new Error('教练ID不存在'))
    } else {
      callback()
    }
  } catch (error) {
    callback(new Error('教练ID验证失败'))
  }
}

// 添加表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入课程名称', trigger: 'blur' },
    { min: 2, max: 50, message: '课程名称长度应在2-50个字符之间', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择课程分类', trigger: 'change' }
  ],
  expertId: [
    { required: true, message: '请输入教练ID', trigger: 'blur' },
    { type: 'number', message: '教练ID必须为数字', trigger: 'blur' },
    { validator: validateExpertId, trigger: 'blur' }
  ],
  level: [
    { required: true, message: '请选择难度等级', trigger: 'change' }
  ],
  duration: [
    { required: true, message: '请输入课程时长', trigger: 'blur' },
    { pattern: /^\d+$/, message: '请输入有效的时长（分钟）', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入课程介绍', trigger: 'blur' },
    { min: 10, message: '课程介绍不能少于10个字符', trigger: 'blur' }
  ],
  coverImage: [
    { required: true, message: '请输入封面图片URL', trigger: 'blur' },
    { pattern: /^(http|https):\/\/[^ "]+$/, message: '请输入有效的图片URL', trigger: 'blur' }
  ]
}

// 获取课程列表
const fetchCourses = async () => {
  try {
    const res = await getCourseList({
      page: currentPage.value,
      pageSize: pageSize.value
    })
    if (res && Array.isArray(res)) {
      const coursesWithInstructor = res.map(item => {
        return {
          courseId: item.courseId,
          title: item.title,
          category: item.category,
          expertId: item.expertId,
          instructor: item.expertName || '未知教练',
          level: item.level,
          duration: `${item.duration}分钟`,
          status: item.status,
          description: item.description,
          coverImage: item.coverImage
        }
      })
      
      courses.value = coursesWithInstructor
      total.value = res.length
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error('获取课程列表失败')
  }
}

// 过滤课程列表
    const filteredCourses = computed(() => {
      return courses.value.filter(course => 
        course.title.includes(searchQuery.value) ||
        course.instructor.includes(searchQuery.value) ||
        course.category.includes(searchQuery.value)
      )
    })

// 获取难度标签类型
    const getLevelType = (level) => {
      const types = {
    '基础课程': 'info',
    '进阶课程': 'warning'
      }
      return types[level] || ''
    }

// 获取状态标签类型
    const getStatusType = (status) => {
      const types = {
    '已发布': 'success',
        '已下架': 'info',
    '未发布': 'warning'
      }
      return types[status] || ''
    }

// 添加课程
    const handleAdd = () => {
      dialogType.value = 'add'
      courseForm.value = {
    courseId: '',
        title: '',
        category: '',
    expertId: '',
        instructor: '',
    level: '基础课程',
        duration: '',
        description: '',
    coverImage: '',
    status: '未发布'
      }
      dialogVisible.value = true
    }

// 编辑课程
    const handleEdit = (row) => {
      dialogType.value = 'edit'
  courseForm.value = {
    ...row,
    courseId: row.courseId,
    expertId: row.expertId,
    instructor: row.instructor
  }
      dialogVisible.value = true
    }

// 删除课程
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该课程吗？', '提示', {
      type: 'warning'
    })
    await deleteCourse(row.courseId)
    ElMessage.success('删除成功')
    fetchCourses() // 重新获取列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除课程失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  courseFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        // 先验证教练是否存在
        try {
          const expertInfo = await getExpertInfo(parseInt(courseForm.value.expertId))
          if (!expertInfo) {
            ElMessage.error('教练ID不存在，请检查')
            return
          }
        } catch (error) {
          ElMessage.error('教练ID不存在，请检查')
          return
        }

        // 构建提交的数据
        const submitData = {
          ...courseForm.value,
          expertId: parseInt(courseForm.value.expertId),
          duration: parseInt(courseForm.value.duration)
        }

        if (dialogType.value === 'add') {
          delete submitData.courseId
          const response = await addCourse(submitData)
          if (response || response === true) {
            ElMessage.success('添加成功')
            dialogVisible.value = false
            fetchCourses()
          } else {
            ElMessage.error('添加失败')
          }
        } else {
          const response = await updateCourse(submitData)
          if (response || response === true) {
            ElMessage.success('修改成功')
      dialogVisible.value = false
            fetchCourses()
          } else {
            ElMessage.error('修改失败')
          }
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(error.response?.data?.message || '操作失败')
      }
    }
  })
}

// 分页相关方法
    const handleSizeChange = (val) => {
      pageSize.value = val
  fetchCourses()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
  fetchCourses()
    }

// 组件挂载时获取专家列表
onMounted(() => {
  fetchCourses()
})
</script>

<style scoped>
.fitness-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.operation-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}
</style> 